package org.otarriinae.security.error;

import org.orarriinae.common.web.result.ResponseBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;

/**
 * @author xj
 * @since 1.0
 */
@RestController
public class SecurityErrorController implements ErrorController {
    private static final String PATH = "/error";

    @Autowired(required = false)
    private ErrorAttributes errorAttributes;

    @RequestMapping(value = PATH)
    ResponseBean<String> error(HttpServletRequest request, HttpServletResponse response) {

        Map<String, Object> errorMap = getErrorAttributes(request);
        //定义返回格式
        ResponseBean<String> d= new ResponseBean<String>();
        d.setMessage(Objects.requireNonNull(errorMap.get("message")).toString());
        d.setErrorCode(Objects.requireNonNull(errorMap.get("status")).toString());
        response.setStatus(HttpServletResponse.SC_OK);
        return d;
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }

    /**
     * 获取请求参数
     * @param request
     * @return
     */
    private Map<String, Object> getErrorAttributes(HttpServletRequest request) {
        WebRequest requestAttributes = new ServletWebRequest(request);
        return errorAttributes.getErrorAttributes(requestAttributes,false);
    }
}
